import { useEffect, useState } from 'react';
import './Supplier.css';
import supplierApi from '@/apis/supplierApi';
import { useNavigate, useParams } from 'react-router-dom';
import { Button, Card, Image, List, Sidebar, Toast } from 'react-vant';
import { ResponseSuppliersDto } from '@/types/dto/supplierDto';
import { getGoodsImagePath, getSuppliersImagePath } from '@/utils/common';
import { Add, LocationO } from '@react-vant/icons';
import goodApi from '@/apis/goodApi';
import MyPromotePrice from '@/components/MyPromotePrice';
import chartApi from '@/apis/chartApi';

const Supplier: React.FC = () => {
  const { id } = useParams();
  const [supplier, setSupplier] = useState<ResponseSuppliersDto>();
  const [goodTypes, setGoodTypes] = useState<goodTypeCountDto[]>();
  const [currentActive, setCurrentActive] = useState(0);
  const [goods, setGoods] = useState<ResponseGoodList[]>([]);
  const [loading, setLoading] = useState(false);
  const [finished, setFinished] = useState(false);
  const [page, setPage] = useState(1);
  const naviagte = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
      const res: ResponseApiDto = await supplierApi.getSupplierDetail(parseInt(id as string));
      if (res.status >= 0) {
        setSupplier(res.data);
      }
      const res2: ResponseApiDto = await goodApi.getGoodTypeCount(parseInt(id as string));
      if (res2.status >= 0) {
        setGoodTypes(res2.data);
      }
    };
    fetchData();
  }, []);

  const loadMore = async () => {
    if (loading || finished || !goodTypes?.length) return;

    setLoading(true);

    try {
      const res: ResponseApiDto = await goodApi.getGoodPagnation2(
        page,
        10,
        undefined,
        parseInt(id as string),
        goodTypes[currentActive].gtid,
        1
      );

      if (res.status >= 0) {
        setGoods((prev) => [...prev, ...res.data.data]);
        setPage((prev) => prev + 1);

        // 如果返回的数据少于请求的数量，说明没有更多数据了
        if (res.data.data.length < 10) {
          setFinished(true);
        }
      }
    } catch (error) {
      console.error('加载失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSidebarChange = (active: number) => {
    setCurrentActive(active);
    setGoods([]);
    setPage(1);
    setFinished(false);
  };

  const handleAddChart = async (gid: number) => {
    const res = await chartApi.addChart({ gid: gid });
    if (res.status >= 0) {
      Toast.success('已加入购物车');
    } else {
      Toast.fail(res.message || '无响应');
    }
  };

  return (
    <>
      <div
        className="header-info"
        style={{
          backgroundImage: `url(${getSuppliersImagePath(
            supplier?.id as number,
            supplier?.photo.split(',')[0] as string
          )})`,
        }}
      >
        <Card round className="info-card">
          <div className="card-image">
            <Image
              src={getSuppliersImagePath(supplier?.id as number, supplier?.avatar as string)}
            />
          </div>
          <div className="card-info">
            <div className="card-name">{supplier?.shopName}</div>
            <div className="card-address">
              <LocationO />
              {supplier?.address}
            </div>
          </div>
        </Card>
      </div>
      <div className="body-content">
        <Sidebar value={currentActive} onChange={handleSidebarChange}>
          {goodTypes?.map((d) => (
            <Sidebar.Item key={d.gtid} title={d.gtName} />
          ))}
        </Sidebar>
        <div className="good-list2">
          <List onLoad={loadMore} finished={finished} offset={100}>
            {goods?.map((d) => (
              <Card key={d.id} className="good-item2" onClick={() => naviagte('/good/' + d.id)}>
                <div className="item2-image">
                  <Image src={getGoodsImagePath(d.id, d.photo)} />
                </div>
                <div>
                  {d.name + ' ' + d.specs}
                  <MyPromotePrice price={d.price} propmotePrice={d.promotePrice} />
                  {d.saleCout}
                  <div className="item2-add-btn">
                    <Add
                      color="red"
                      fontSize={28}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleAddChart(d.id);
                      }}
                    />
                  </div>
                </div>
              </Card>
            ))}
            {finished ? <div className="no-more2">没有更多了</div> : null}
          </List>
        </div>
      </div>
    </>
  );
};

export default Supplier;
